package com.gdglc.java.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;

import com.y2.authprj.bean.auth.model.StaffInfo;
/**
 * 判断用户是否登录,为登录则退出系统
 * @author zwt
 *
 */
public class SessionFilter implements Filter {

	public FilterConfig config;
	
	public static boolean isContains(String container,String[] regx){
		boolean result = false;
		
		for(int i=0;i<regx.length;i++){
			if(container.indexOf(regx[i])!=-1){
				return true;
			}
		}
		return false;
	}
	
	@Override
	public void destroy() {
		this.config=null;
	}
	
	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		// TODO Auto-generated method stub
		HttpServletRequest hrequest = (HttpServletRequest) request;
		HttpServletResponseWrapper wrapper = new HttpServletResponseWrapper((HttpServletResponse) response);
		String logonStrings = config.getInitParameter("logonStrings");
		String includeStrings = config.getInitParameter("includeStrings");
		String redirectPath = hrequest.getContextPath()+config.getInitParameter("redirectPath");//没有登录转向页面
		String disabletestfilter = config.getInitParameter("disabletestfilter");//过滤器是否有效
		//判断不需要经过过滤的url
		String[] logonList = logonStrings.split(";");
		if(this.isContains(hrequest.getRequestURI(),logonList)){
			chain.doFilter(request, response);
			return ;
		}
		
		StaffInfo staff = (StaffInfo)((HttpServletRequest) request).getSession().getAttribute("staffInfo");
		if(staff==null){
			request.getRequestDispatcher("/auth/showLogin").forward(request, response);
			return ;
		}else{
			chain.doFilter(request, response);
			return;
		}
	}
	
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		// TODO Auto-generated method stub
		System.out.println("==========初始化SessionFilter过滤器========");
		config=filterConfig;
	}

}
